package com.ip.user.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

/**
 * SSL信任配置类 - 信任所有证书
 * 
 * 注意：此配置仅适用于开发环境，生产环境应使用正确的证书配置
 * 
 * @author Lingma
 */
@Configuration
public class SSLTrustConfig {
    
    private static final Logger logger = LoggerFactory.getLogger(SSLTrustConfig.class);
    
    /**
     * 初始化时设置信任所有SSL证书
     */
    @PostConstruct
    public void init() {
        logger.warn("初始化SSL信任配置 - 信任所有证书 (仅用于开发环境)");
        trustAllCertificates();
    }
    
    /**
     * 配置信任所有SSL证书
     */
    private void trustAllCertificates() {
        try {
            // 创建信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                    
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        // 信任所有客户端证书
                    }
                    
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        // 信任所有服务器证书
                    }
                }
            };
            
            // 获取SSL上下文并初始化
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            
            // 设置默认的SSL套接字工厂
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            
            // 设置默认的SSL套接字工厂（用于JavaMail）
            SSLContext.setDefault(sslContext);
            
            // 创建并设置信任所有主机的主机名验证器
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    // 信任所有主机
                    return true;
                }
            };
            
            // 设置默认的主机名验证器
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            
            logger.info("SSL证书信任配置已完成 - 所有证书将被信任");
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            logger.error("配置SSL信任时发生错误", e);
        }
    }
}